<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="80px"
      @submit.native.prevent
    >
      <el-form-item label="显示名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入显示名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
        </el-button>
      </el-form-item>
    </el-form>

    <div :class="tableMain" v-show="tableMainShow">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5" style="float: right">
          <el-button
            size="mini"
            @click="tableExtend(1)"
            icon="el-icon-full-screen"
          >
          </el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        stripe
        :header-cell-style="{ background: '#F6F8FB' }"
        @row-click="(row) => checkState(row.id, row.name)"
        :height="maxHeight"
        v-scrollbar="'.el-table__body-wrapper'"
      >
        <el-table-column
          label="系统名称"
          align="center"
          prop="systemName"
          :show-overflow-tooltip="true"
          sortable
        />
        <el-table-column label="ID" align="center" prop="id" sortable />
        <el-table-column
          label="显示名称"
          align="center"
          prop="name"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="描述"
          align="center"
          prop="description"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="类型"
          align="center"
          prop="typeIds"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.typeIds">
              <span
                v-for="(item, index) of scope.row.typeIds.split(',')"
                :key="index"
                >{{ dataFormat("typeid", Number(item)) }},
              </span>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200"
        >
          <template slot-scope="scope">
            <div class="operate-group">
              <span
                style="cursor: pointer; color: #409eff; font-size: 12px"
                type="text"
                class="el-icon-edit"
                :plain="false"
                @click="allotType(scope.row)"
                >分配type</span
              >
              <span
                style="cursor: pointer; color: #409eff; font-size: 12px"
                type="text"
                class="el-icon-edit"
                :plain="false"
                @click="handleUpdate(scope.row)"
                >修改</span
              >
              <span
                style="cursor: pointer; color: #409eff; font-size: 12px"
                type="text"
                class="el-icon-delete"
                :plain="false"
                @click="handleDelete(scope.row)"
                >删除</span
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <resize-bar v-show="tableMainShow && tableDependShow" />
    <div :class="tableDepend" v-show="tableDependShow">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="addState"
            >新增状态</el-button
          >
        </el-col>
        <el-col :span="1.5" style="float: right">
          <el-button
            size="mini"
            @click="tableExtend(2)"
            icon="el-icon-full-screen"
          >
          </el-button>
        </el-col>
        <div class="tableDependTitle">{{ tableDependName }} 的状态</div>
      </el-row>
      <el-table
        v-loading="loading"
        :data="stateList"
        stripe
        @selection-change="handleSelectionChange"
        :header-cell-style="{ background: '#F6F8FB' }"
        :height="maxHeight"
        v-scrollbar="'.el-table__body-wrapper'"
      >
        <el-table-column label="ID" align="center" prop="id" width="90" />
        <el-table-column
          label="系统名称"
          align="center"
          prop="systemName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="显示名称"
          align="center"
          prop="name"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="状态"
          align="center"
          prop="description"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="顺序号"
          align="center"
          prop="sort"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <div class="operate-group">
              <span
                style="cursor: pointer; color: #409eff; font-size: 12px"
                type="text"
                class="el-icon-edit"
                :plain="false"
                @click="stateUpdate(scope.row)"
                >修改</span
              >
              <span
                style="cursor: pointer; color: #409eff; font-size: 12px"
                type="text"
                class="el-icon-delete"
                :plain="false"
                @click="stateDelete(scope.row.id)"
                >移除</span
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="stateTotal > 0"
        :total="stateTotal"
        :page.sync="queryStateParams.pageNum"
        :limit.sync="queryStateParams.pageSize"
        @pagination="getStateList"
      />
    </div>

    <!-- 添加或修改策略对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      v-dialogDrag
      v-if="open"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="form.systemName" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="显示名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="版本" prop="revision">
          <el-input v-model="form.revision" placeholder="请输入版本" />
        </el-form-item>
        <el-form-item label="版本规则" prop="revisionRule">
          <el-input v-model="form.revisionRule" placeholder="请输入版本规则" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改分类属性对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="stateOpen"
      width="500px"
      append-to-body
      v-dialogDrag
      v-if="stateOpen"
      :close-on-click-modal="false"
    >
      <el-form
        ref="stateForm"
        :model="stateForm"
        :rules="stateRules"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item label="系统名称" prop="systemName">
          <el-input
            v-model="stateForm.systemName"
            placeholder="请输入系统名称"
          />
        </el-form-item>
        <el-form-item label="显示名称" prop="name">
          <el-input v-model="stateForm.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input v-model="stateForm.sort" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="是否生效">
          <el-radio-group v-model="stateForm.effect">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="stateForm.description" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStateForm">确 定</el-button>
        <el-button @click="cancelState">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 给策略分配类型对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="allotOpen"
      width="500px"
      append-to-body
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <el-form
        ref="allotForm"
        :model="allotForm"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item label="类型">
          <el-tree
            :data="typeOptions"
            show-checkbox
            ref="types"
            node-key="id"
            default-expand-all
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllotForm">确 定</el-button>
        <el-button @click="cancelAllot">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  policyList,
  getPolicy,
  delPolicy,
  addPolicy,
  updatePolicy,
  listState,
  delState,
  getState,
  updateState,
  addStateForm,
} from "@/api/pms/policy";

export default {
  inject: ["app"],
  name: "Type",
  components: {
    resizeBar: () => import("@/views/components/resizeBar"),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      stateTotal: 0,
      tableMain: "table-main",
      tableDepend: "table-depend",
      tableDependWidth: 0.49,
      tableMainShow: true,
      tableDependShow: true,
      // 分类管理表格数据
      list: [],
      stateList: [],
      // 弹出层标题
      title: "",
      policyID: "",
      tableDependName: "",
      // 是否显示弹出层
      open: false,
      stateOpen: false,
      allotOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: this.$store.state.user.pageSize||30,
        name: undefined,
        systemName: undefined,
      },
      queryStateParams: {
        pageNum: 1,
        pageSize: this.$store.state.user.pageSize||30,
        policyid: undefined,
      },
      // 表单参数
      form: {},
      stateForm: {},
      allotForm: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        systemName: [
          { required: true, message: "系统名称不能为空", trigger: "blur" },
        ],
        parentid: [
          { required: true, message: "父ID不能为空", trigger: "blur" },
        ],
      },
      stateRules: {
        systemName: [
          { required: true, message: "系统名称不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        sort: [{ required: true, message: "顺序号不能为空", trigger: "blur" }],
      },
      typeOptions: {},
    };
  },
  created() {
    this.getList();
    let optionData = JSON.parse(sessionStorage.getItem("optionsData"));
    let typeArray = optionData["typeOptions"];
    typeArray.forEach((item, index) => {
      typeArray[index] = this.normalizer(item);
    });
    this.typeOptions = this.handleTree(typeArray, "id", "parentId");
  },
  computed: {
    maxHeight() {
      return this.app.screenHeight - 270;
    },
  },
  methods: {
    /** 查询分类管理列表 */
    getList() {
      this.loading = true;
      policyList(this.queryParams).then((response) => {
        this.list = response.rows;
        this.total = response.total;
        if (response.rows.length > 0) {
          this.tableDependName = response.rows[0].name;
          this.policyID = response.rows[0].id;
          this.queryStateParams.policyid = response.rows[0].id;
          this.getStateList();
        } else {
          this.stateList = [];
          this.stateTotal = 0;
        }
        this.loading = false;
      });
    },
    getStateList() {
      this.loading = true;
      listState(this.queryStateParams).then((response) => {
        this.stateList = response.rows;
        this.stateTotal = response.total;
        this.loading = false;
      });
    },
    checkState(id, name) {
      this.tableDependName = name;
      this.policyID = id;
      this.queryStateParams.policyid = id;
      this.getStateList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        systemName: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加策略";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPolicy(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改策略";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePolicy(this.form).then((response) => {
              if (response.code === 200) {
                this.resetForm("form");
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addPolicy(this.form).then((response) => {
              if (response.code === 200) {
                this.resetForm("form");
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除编号为"' +
          (Array.isArray(ids) && ids.length > 2 ? ids[0] + "等" : ids) +
          '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delPolicy(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    stateDelete(Id) {
      const Ids = Id || this.ids;
      this.$confirm(
        '是否确认删除状态编号为"' +
          (Array.isArray(Ids) && Ids.length > 2 ? Ids[0] + "等" : Ids) +
          '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delState(Ids);
        })
        .then(() => {
          this.getStateList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    addState() {
      if (!this.policyID) {
        this.msgError("请选择策略");
        return false;
      }
      this.stateForm.effect = "1";
      this.stateOpen = true;
      this.title = "添加策略状态";
    },
    /** 修改按钮操作 */
    stateUpdate(row) {
      getState(row.id).then((response) => {
        this.stateForm = response.data;
        this.stateOpen = true;
        this.title = "修改策略状态";
      });
    },
    // 属性取消按钮
    cancelState() {
      this.stateOpen = false;
      this.stateForm = {}
      // this.resetForm("stateForm");
    },
    /** 属性提交按钮 */
    submitStateForm: function () {
      this.$refs["stateForm"].validate((valid) => {
        if (valid) {
          if (this.stateForm.id != undefined) {
            this.stateForm.policyid = this.policyID;
            updateState(this.stateForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.resetForm("stateForm");
                this.stateOpen = false;
                this.getStateList();
              }
            });
          } else {
            this.stateForm.policyid = this.policyID;
            addStateForm(this.stateForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.resetForm("stateForm");
                this.stateOpen = false;
                this.getStateList();
              }
            });
          }
        }
      });
    },
    /** 分配type操作 */
    allotType(row) {
      this.allotForm.id = row.id;
      var typeIdsIntArr = [];
      if (row.typeIds) {
        var typeIdsArr = row.typeIds.split(",");
        typeIdsArr.forEach(function (data, index, arr) {
          typeIdsIntArr.push(data);
        });
      }
      this.allotOpen = true;
      this.title = "分配类型";
      this.$nextTick(() => {
        this.$refs.types.setCheckedKeys(typeIdsArr);
      });
    },
    /** 转换数据结构 */
    normalizer(node) {
      return {
        id: node.id,
        label: node.description,
        parentId: node.parentid,
        name: node.name,
      };
    },
    // 属性取消按钮
    cancelAllot() {
      this.allotOpen = false;
      this.reset();
    },
    /** 属性提交按钮 */
    submitAllotForm: function () {
      let typeArrr = this.getAllCheckedKeys();
      this.allotForm.typeIds = typeArrr.join(",");

      this.$refs["allotForm"].validate((valid) => {
        if (valid) {
          if (this.allotForm.id != undefined) {
            updatePolicy(this.allotForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.resetForm("allotForm");
                this.allotOpen = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    // 所有菜单节点数据
    getAllCheckedKeys() {
      // 目前被选中的菜单节点
      // let checkedKeys = this.$refs.types.getHalfCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.types.getCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return halfCheckedKeys;
    },
    tableExtend(type) {
      if (type === 2) {
        if (this.tableDepend === "table-depend") {
          this.tableMainShow = false;
          this.tableDepend = "table-extend";
        } else {
          this.tableMainShow = true;
          this.tableDepend = "table-depend";
        }
      } else {
        if (this.tableMain === "table-main") {
          this.tableDependShow = false;
          this.tableMain = "table-extend";
        } else {
          this.tableDependShow = true;
          this.tableMain = "table-main";
        }
      }
    },
  },
};
</script>
